﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.Interfaces;
using Core.Interfaces.IDAO;
using Core.Interfaces.IPresenters;
using Core.Unity;
using Core.Views;
using Microsoft.Practices.Unity;


namespace Core.Presenters
{
    public class DistrictsPresenter
    {
        private IDistrictDAO _districtDAO;
        private List<IDistrict> _districts = new List<IDistrict>();
        private IAbstractDataView _view;
        
        public DistrictsPresenter(IAbstractDataView view)
        {
            _districtDAO = ResolverContainer.Resolver.Resolve<IDistrictDAO>();
            view.AddRecord += AddRecord;
            view.Refreh += Refreh;
            view.UpdateRecord += Update;
            view.DeleteRecord += DeletRecord;
            _districts = _districtDAO.GetAll(false);
            view.Data.DataSource = _districts;
            view.Data.ResetBindings(true);
            view.ViewName = "Справочник районов";
            _view = view;
            view.Show();
        }

        private void AddRecord(object sender,EventArgs eventArgs )
        {
            var district = new DistrictPresenter(new DistrictView());
            Refreh(this,null);
        }

        private void Update(object sender, EventArgs eventArgs)
        {
            if (_view.Data.Current != null)
            {
                var district = _view.Data.Current;
                new DistrictPresenter(new DistrictView(), (IDistrict) district);
            }
        }

        private void DeletRecord(object sender, EventArgs eventArgs)
        {
            if (_view.Data.Current != null)
            {
                var current = _view.Data.Current;
                _districtDAO.Delete((IDomainObject) current);
                Refreh(this,null);
            }
        }

        private void Refreh(object sender, EventArgs eventArgs )
        {
            _districts = _districtDAO.GetAll(false);
            _view.Data.DataSource = _districts;
        }
    }
}
